package com.example.capsule.config;

import com.aliyun.dysmsapi20170525.Client;
import com.aliyun.teaopenapi.models.Config;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class SmsConfig {
    private static final Logger logger = LoggerFactory.getLogger(SmsConfig.class);

    @Value("${sms.aliyun.endpoint:dysmsapi.aliyuncs.com}")
    private String endpoint;

    @Bean
    public Client smsClient() {
        try {
            // 从环境变量读取AccessKey
            String accessKeyId = System.getenv("ALIBABA_CLOUD_ACCESS_KEY_ID");
            String accessKeySecret = System.getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET");

            if (accessKeyId == null || accessKeySecret == null) {
                logger.error("阿里云AccessKey环境变量未配置！");
                logger.error("请设置 ALIBABA_CLOUD_ACCESS_KEY_ID 和 ALIBABA_CLOUD_ACCESS_KEY_SECRET 环境变量");
                throw new IllegalStateException("阿里云AccessKey环境变量未配置");
            }

            logger.info("成功加载阿里云短信服务配置");
            logger.info("Endpoint: {}", endpoint);
            logger.info("AccessKey ID: {}...", accessKeyId.substring(0, Math.min(accessKeyId.length(), 8)));

            Config config = new Config()
                    .setAccessKeyId(accessKeyId)
                    .setAccessKeySecret(accessKeySecret)
                    .setEndpoint(endpoint);

            return new Client(config);

        } catch (Exception e) {
            logger.error("初始化阿里云短信客户端失败", e);
            throw new RuntimeException("短信服务初始化失败", e);
        }
    }
}